<template>
  <q-dialog v-model="visible">
    <q-card style="min-width: 22rem">
      <q-card-section>
        <q-file
          outlined
          v-model="picture"
          :label="$t(lang + '点击此处重新上传地图图片')"
          clearable
        >
          <template v-slot:before>
            <div class="text-h6">{{ $t(lang + "上传地图图片") }}</div>
          </template>
        </q-file>
      </q-card-section>
      <q-slide-transition>
        <div v-if="iconBase64 !== null">
          <q-separator />
          <q-card-section>
            <q-img :src="iconBase64" />
          </q-card-section>
          <div class="bg-primary">
            <q-btn
              no-caps
              class="full-width text-h6"
              stretch
              color="primary"
              @click="modify"
              :label="$t(lang + '录入地图图片')"
            />
          </div>
        </div>
      </q-slide-transition>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import { useAPIStore } from "stores/api";
import { api } from "boot/axios";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";

const t = useI18n().t;
const lang = "mapIndex.MapImgUploader.";
defineExpose({ show });
const $q = useQuasar();
const visible = ref(false);
const picture = ref(null);
const iconBase64 = ref(null);
const map = ref({});
watch(picture, (value) => {
  if (value !== null) {
    const reader = new FileReader();
    reader.readAsDataURL(value);
    reader.onload = () => {
      iconBase64.value = reader.result;
    };
    reader.onerror = function (error) {
      console.log("Error: ", error);
    };
  } else {
    iconBase64.value = null;
  }
});
function show(data) {
  map.value = data;
  // iconBase64.value = 'data:image/png;base64,' + map.value.mapBase64
  visible.value = true;
}
// 修改地图
function modify() {
  map.value.mapBase64 = iconBase64.value.slice(22);
  api.put(useAPIStore().mapUrl + "map", map.value).then((rs) => {
    if (rs.data === "modified") {
      $q.notify({
        message: t(lang + "地图修改成功"),
        type: "positive",
      });
      visible.value = false;
    }
  });
}
</script>
